<?php

/**
 * DealsController is the default controller for this application
 */
class DealsController extends ControllerBase {
	
	/**
	 * Admin Deals Data Service Object
	 * @var dealsDataService object
	 */
	private $grouponDataService;
	private $dealsDataService;
	public $grouponCategoryDataService = null;
	/**
	 *
	 * UsersDataService Object
	 * @var UsersDataService object
	 */
	public $userDataService = null;
	/**
	 * DealsController Constructor
	 */
	public function __construct() {
		parent::__construct ();
		
		// Set deals name
		$this->setPageName ( 'admin_deals' );
		
		// Init Authentication class
		$authentication = new Authentication ();
		
		// Only administrator can right
		if (!($authentication->isAdministrator () == true || $authentication->getUserType() == ROLE_DEALMANAGER)) {
			// Go to login groupon
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/';
			CommonUtils::redirect ( $url );
		}
		
		// Get status list of deals category
		//		$this->smarty->assign('statusList', DealsEntity::getStatusList());
		

		// New groupon Data Service
		$this->grouponDataService = new GrouponDataService ();
		// new deals category Data Service
		$this->grouponCategoryDataService = new GrouponCategoryDataService ();
		// New deals Data Service
		$this->dealsDataService = new DealsDataService ();
		$this->smarty->assign('pageName', 'deal');
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing deals of the site. Return list of all deals category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function indexAction() {
		$arrElement = array ();
		$arrElementAll = array ();
		$status = -1;
		if($this->getQuery('status') != ''){
			$arrElement ['status'] = (int)$this->getQuery ( 'status' , 0);
			$arrElementAll['D.status'] = (int)$this->getQuery ( 'status', 0);
			$status = (int)$this->getQuery ( 'status', 0);
		}
		
		$where = '';
		
		if($this->getPost('submit') == 'Tìm'){
			if($this->getPost('groupon_name') != ''){
				$where .= ' AND G.groupon_name LIKE "%'.$this->getPost('groupon_name').'%"';				
			}
			$this->smarty->assign('groupon_name', $this->getPost('groupon_name'));
			if($this->getPost('started_deal') != ''){
				$where .=' AND D.started_deal > '. $this->getPost('started_deal');					
			}
			$this->smarty->assign('started_deal', $this->getPost('started_deal'));	
			if($this->getPost('expired_deal') != ''){
				$where .=' AND D.expired_deal > '. $this->getPost('expired_deal');
			}
			$this->smarty->assign('expired_deal', $this->getPost('expired_deal'));
			if($this->getPost('category') != ''){
				$where .=' AND GC.id = '. $this->getPost('category');				
			}
			$this->smarty->assign('category', $this->getPost('category'));	
			if($this->getPost('deal_status') != '-1'){
				$arrElement['status'] = (int)$this->getPost('deal_status');
				$where .=' AND D.status = '. $this->getPost('deal_status');	
				$status = $this->getPost('deal_status');					
			}

		}
		$this->smarty->assign('deal_status', $status);
		$numRecordPerPage = ITEM_PER_PAGE;
		// Pager
		$start = $this->getQuery ( 'start', 0 );
		if ($start == '' || $start < 0) {
			$start = 0;
		}
		
		// Get Totals Templates
		$totals = $this->dealsDataService->getTotals ( $arrElement );
		
		$itemList = $this->dealsDataService->getItemsAll ( $arrElement, 'D.id desc', $start, $numRecordPerPage, $where );
		if ($start > $totals) {
			$start = 0;
		}
		$link = Zend_Registry::get ( 'config' )->APPLICATION_URL . "/Admin/Deals/Index/status/". $status;
		$pageLink = '';
		if ($totals > $numRecordPerPage) {
			$pageUtils = new PagerUtils ( $start, $totals, $numRecordPerPage, 10, $link );
			$pageLink = $pageUtils->writePagesLinks ( 0, 'start' );
			$pageLink .= "<br><span class=\"paing_text_nolink\">" . $pageUtils->writePagesCounter () . "</span>";
		}
		
		$this->smarty->assign ( 'itemList', $itemList );
		$this->smarty->assign ( 'this', $this );
		$this->smarty->assign ( 'pageLink', $pageLink );
		$this->smarty->assign ( 'dealEntity', new DealsEntity () );
		$this->smarty->assign('dealStatusList', DealsEntity::getStatusList());
		$this->smarty->assign('categoryList', $this->grouponCategoryDataService->getItems(array()));
		// create session
		$this->createActionKey ();
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Deals/index.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
		
	}
	
	/**
	 * Dispplay List of deals_category
	 * landing deals of the site. Return list of all deals_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function listAction() {
		
		
	}
	
	public function showdealsAction() {
		date_default_timezone_set ( 'UTC' );
		//get deals of Groupon
		$grouponId = $this->getQuery ( 'groupon_id', 0 );
		$grouponEntity = $this->grouponDataService->getById ( $grouponId );
		$dealsEntities = $this->dealsDataService->getDealsOfGroupon ( $grouponId );
		//    		$time =  strtotime(date('Y-m-d h:i:s')) + 3600;
		//		  $offset=7*60*60; //converting 7 hours to seconds.
		//		  $dateFormat="d-m-Y H:i:s";
		//		  $timeNdate=gmdate($dateFormat, time()+$offset);
		//		  echo $timeNdate;
		$this->smarty->assign ( 'dealsEntities', $dealsEntities );
		$this->smarty->assign ( 'grouponEntity', $grouponEntity );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Deals/showdeals.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	public function approveAction() {
		$deal_id = $this->getPost ( 'deal_id', 0 );

		$dealsEntity = $this->dealsDataService->getById ( $deal_id );
		$success = 1;
		if (is_null ( $dealsEntity )) {
			$success = 0;
			exit ();
		} else {
			$dealsEntity->started_deal = date ( 'Y-m-d H:i:s' );
			$dealsEntity->expired_deal = date ( 'Y-m-d H:i:s', (time () + ($dealsEntity->duration * 60 * 60)) );
			$dealsEntity->status = 1;
			$this->dealsDataService->update ( $dealsEntity );
			
			$content = CONTENT_MAIL_SUBSCRIBE;
			
			//send mail
			try {
				$mail = new SENDMAIL ();
				$res = $mail->send ( 'thanhphi89@gmail.com', 'tran thanh phi', 'Deal hấp dẫn từ MuaHội', $content );
			} catch ( Exception $ex ) {
			
			}
			
			
			$return = array ("success" => $success );
			echo Zend_Json::encode ( $return );
			exit ();
		}
	}
	public function editAction(){
		$aError = array();
		$bError = false;
				// Get id of groupon
		$id = $this->getPost ( 'id' );
		if (empty ( $id )) {
			$id = $this->getQuery ( 'id' );
		}
		$dealEntity = $this->dealsDataService->getById($id);
		if($this->getPost('save', '') != ''){
			$fine_print = $this->getPost('fine_print', '');
			if($fine_print == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Diều kiện mua hàng không bỏ trống'));
			}
			$original_price = $this->getPost('original_price', '');
			if(!is_numeric($original_price) ){
				$bError =  true;
				$aError = array_merge($aError, array('Giá gốc phải là số và lớn hơn 0'));
			};
			$sale_price = $this->getPost('sale_price', '');
			if(!is_numeric($sale_price) || !(intval($sale_price) > 0) || !(intval($sale_price) < intval($original_price))){
				$bError =  true;
				$aError = array_merge($aError, array('Giá bán phải là số, lớn hơn 0 và nhỏ hơn giá gốc'));
			}
			$min_bought = $this->getPost('min_bought', '');
			if(!is_numeric($min_bought) || !(intval($min_bought) > 0)){
				$bError =  true;
				$aError = array_merge($aError, array('Số lượng bán tối thiểu phải là số và lớn hơn 0'));
			}
			$max_bought = $this->getPost('max_bought', '');
		if(!is_numeric($max_bought) || !(intval($max_bought) >= intval($min_bought))){
				$bError =  true;
				$aError = array_merge($aError, array('Số lượng bán tối đa phải là số và lớn hơn số lượng bán tối thiểu'));
			}
			$duration = $this->getPost('duration', '');
		if(!is_numeric($duration) || !(intval($duration) > 0)){
				$bError =  true;
				$aError = array_merge($aError, array('Thời gian bán phải là số và lớn hơn 0'));
			}
			if(!$bError){	
				$dealEntity->fine_print = $fine_print;
				$dealEntity->original_price = $original_price;
				$dealEntity->sale_price = $sale_price;
				$dealEntity->min_bought = $min_bought;
				$dealEntity->max_bought = $max_bought;
				$dealEntity->duration = $duration;
				
				$this->dealsDataService->update($dealEntity);
			}
		}
		
		$this->smarty->assign ( 'aError', $aError);
		$this->smarty->assign ( 'bError', $bError );
		$this->smarty->assign('deal', $dealEntity);

		$this->smarty->assign ('SMARTY_CONTENT_PATH','Admin/Deals/edit.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	public function renewAction(){
		$aError = array();
		$bError = false;
		$groupon_id = $this->getPost ( 'groupon_id' );
		if (empty ( $groupon_id )) {
			$groupon_id = $this->getQuery ( 'groupon_id' );
		}
		
		if($this->getPost('save', '') != ''){
			$fine_print = $this->getPost('fine_print', '');
			if($fine_print == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Diều kiện mua hàng không bỏ trống'));
			}
			$original_price = $this->getPost('original_price', '');
			if(!is_numeric($original_price) ){
				$bError =  true;
				$aError = array_merge($aError, array('Giá gốc phải là số và lớn hơn 0'));
			};
			$sale_price = $this->getPost('sale_price', '');
			if(!is_numeric($sale_price) || !(intval($sale_price) > 0) || !(intval($sale_price) < intval($original_price))){
				$bError =  true;
				$aError = array_merge($aError, array('Giá bán phải là số, lớn hơn 0 và nhỏ hơn giá gốc'));
			}
			$min_bought = $this->getPost('min_bought', '');
			if(!is_numeric($min_bought) || !(intval($min_bought) > 0)){
				$bError =  true;
				$aError = array_merge($aError, array('Số lượng bán tối thiểu phải là số và lớn hơn 0'));
			}
			$max_bought = $this->getPost('max_bought', '');
		if(!is_numeric($max_bought) || !(intval($max_bought) >= intval($min_bought))){
				$bError =  true;
				$aError = array_merge($aError, array('Số lượng bán tối đa phải là số và lớn hơn số lượng bán tối thiểu'));
			}
			$duration = $this->getPost('duration', '');
		if(!is_numeric($duration) || !(intval($duration) > 0)){
				$bError =  true;
				$aError = array_merge($aError, array('Thời gian bán phải là số và lớn hơn 0'));
			}
			if(!$bError){				
				$dealsEntity = $this->dealsDataService->beforeCreate ();
					$dealsEntity->groupon_id = $groupon_id;
					$dealsEntity->deal_name = '';
					$dealsEntity->address_id = 1;
					$dealsEntity->fine_print = $fine_print;
					$dealsEntity->original_price = $original_price;
					$dealsEntity->sale_price = $sale_price;
					$dealsEntity->bought_count = 0;
					$dealsEntity->started_deal = '';
					$dealsEntity->expired_deal = '';
					$dealsEntity->tipped_date = '';
					$dealsEntity->rating_average = 0;
					$dealsEntity->rating_count = 0;
					$dealsEntity->comment_count = 0;
					$dealsEntity->payment_type = 'test';
					$dealsEntity->min_bought = $min_bought;
					$dealsEntity->max_bought = $max_bought;
					$dealsEntity->status = 0;
					$dealsEntity->duration = $duration;
					$dealId = $this->dealsDataService->create ( $dealsEntity );
					
					$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Deals/showdeals/groupon_id/'. $groupon_id;
					CommonUtils::redirect ( $url );
			}
		}
		
		$this->smarty->assign ( 'aError', $aError);
		$this->smarty->assign ( 'bError', $bError );
		$this->smarty->assign ( 'groupon_id', $groupon_id );	
		$this->smarty->assign ('SMARTY_CONTENT_PATH','Admin/Deals/renew.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
}
